<template>
  <div class="comments-from-box page" ref="webview">
    <van-nav-bar title="意见反馈" class="bg_white" left-arrow @click-left="$router.go(-1)" />
    <div class="content">
      <div class="input">
        <van-field v-model="form.content" rows="5" autosize type="textarea" placeholder="请反馈您的问题，您的反馈会在24小时内得到 回复！" />
      </div>
      <!-- <div class="input">
        <van-field label="联系方式" v-model="message" type=" text " placeholder="请输入你的联系方式 " />
      </div> -->
      <div class="upload">
        <template v-if="isApp">
          <div class="images">
            <template v-if="form.gallery">
              <img :src="form.gallery" @click.stop="showIMG()" />
            </template>
            <span class="van-icon van-icon-photograph van-uploader__upload-icon photograph" @click="openAction()" v-if="!form.gallery"></span>
            <span class="van-icon van-icon-clear van-uploader__preview-delete" v-if="form.gallery" @click="removeImg()"></span>
          </div>
        </template>
        <template v-else>
          <div class="images">
            <van-uploader class="uploader " name="images " v-model="galleryList" :after-read="afterRead" :max-count="9" />
          </div>
        </template>
        <div class="loading" v-if="isFrontLoading">
          <van-loading size="24px" color="#ffffff"></van-loading>
        </div>
      </div>
    </div>
    <div class="addCard ">
      <van-button color="#ff0034 " class="btn " :loading="isLoading" @click.native="submit">发送</van-button>
    </div>
    <van-image-preview v-model="showPreview " closeable :showIndex="false " :class="{isApp:isApp} " v-if="isApp " :images="images " />
    <van-action-sheet v-model="isAction" :round="false " @select="selectAction" cancel-text="取消" :actions="actions" description="上传反馈图片 " />
  </div>
</template>
<script>
import mixins from '@/utils/mixins';
export default {
  name: 'feedback',
  data () {
    return {
      rateValue: 1,
      message: '',
      showPreview: false,
      images: [],
      form: {
        gallery: '',
        content: ''
      },
      galleryList: [],
      isFrontLoading: false,
      imgType: '', // 区分打开的是相机还是相册
      actions: [{ name: '拍照' }, { name: '相册' }],
      isAction: false
    };
  },
  mixins: [mixins],
  computed: {
    isApp: {
      get () {
        return !!localStorage.getItem('isApp') || !!this.$route.query.isApp;
      }
    }
  },
  created () { },
  mounted () { },
  methods: {
    afterRead (data, detail) {
      var fileFormData = new FormData();
      var FiletypeName = null;
      var fileData = null;
      if (!this.isApp) {
        FiletypeName = data.content.replace(/data:image\/([^;]+).*/i, '$1');
      } else {
        fileData = 'data:image/' + detail + ';base64,' + data;
      }
      fileFormData.append('fileType', !this.isApp ? FiletypeName : detail);
      fileFormData.append('base64', !this.isApp ? data.content : fileData);
      this.$set(this, 'isFrontLoading', true); // loading加载
      // 非APP用web上传
      if (!this.isApp) {
        this.fileUploadAccountImg(fileFormData, detail.name);
      } else {
        return fileFormData;
      }
    },
    // 显示图片
    showIMG () {
      this.images = [this.form.gallery];
      this.showPreview = true;
    },
    removeImg () {
      this.$set(this.form, 'gallery', '');
    },
    // 上传反馈图集
    fileUploadAccountImg (fileFormData, type) {
      this.$API.global.cardFileUpload(fileFormData).then(res => {
        if (!res.data.code) {
          var _res = res.data;
          if (!this.isApp) {
            this.galleryList = [{ url: _res.src }];
          }
          this.$set(this.form, 'gallery', _res.src);
          this.isFrontLoading = false;
        } else {
          this.$toast(res.data.message);
          this.isFrontLoading = false;
        }
      });
    },
    // 文件流转base64
    toBase64 (data, callbark) {
      var trans = window.api.require('trans');
      trans.decodeImgToBase64(
        {
          imgPath: 'widget://' + data
        },
        (ret, err) => {
          if (ret.status) {
            callbark && callbark(ret.base64Str.replace(/[\r\n]/g, ''));
          } else {
            console(JSON.stringify(err));
          }
        }
      );
    },
    getPicture (type) {
      window.api.getPicture({
        sourceType: type === 'camera' ? 'camera' : 'album', // 从相册中选择
        encodingType: 'jpg',
        mediaValue: 'pic',
        allowEdit: false,
        destinationType: 'base64', // 返回base64地址
        quality: 70,
        saveToPhotoAlbum: true
      }, (ret, err) => {
        this.isAction = false;
        var fileType = ret.base64Data.replace(/data:image\/([^;]+).*/i, '$1');
        var base64Data = ret.base64Data.replace(/^data:image\/\w+;base64,/, '');
        var fileFormData = this.afterRead(base64Data, fileType);
        this.fileUploadAccountImg(fileFormData, this.imgType);
      }
      );
    },
    // 打开系统相册
    UIMediaScanner () {
      var UIAlbumBrowser = window.api.require('UIAlbumBrowser');
      UIAlbumBrowser.imagePicker(
        {
          max: 1,
          showCamera: false,
          styles: {
            bg: '#fff',
            mark: {
              icon: '',
              position: 'bottom_left',
              size: 20
            },
            nav: {
              bg: 'rgba(0,0,0,0.6)',
              titleColor: '#fff',
              titleSize: 18,
              cancelColor: '#fff',
              cancelSize: 16,
              finishColor: '#fff',
              finishSize: 16
            }
          },
          rotation: true
        },
        ret => {
          if (ret) {
            this.isAction = false;
            if (ret.eventType === 'nextStep') {
              var list = ret.list[0];
              this.toBase64(list.path, base64Str => {
                var fileFormData = this.afterRead(base64Str, list.suffix);
                this.fileUploadAccountImg(fileFormData, this.imgType);
              });
              UIAlbumBrowser.closePicker();
            }
          }
        }
      );
    },
    selectAction (action, index) {
      if (!index) {
        this.getPicture('camera');
      } else {
        this.UIMediaScanner();
      }
    },
    openAction () {
      this.isAction = true;
    },
    // 上传反馈
    submit () {
      this.isLoading = true;
      if (!this.form.content) {
        this.$toast('请输入反馈问题');
        this.isLoading = false;
        return;
      }
      if (!this.form.gallery) {
        this.$toast('请上传反馈图片');
        this.isLoading = false;
        return;
      }
      this.$API.user.feedback(this.form).then(res => {
        if (!res.code) {
          this.$router.push({ path: '/prompt', query: { type: 1 } });
          this.isLoading = false;
        } else {
          this.$toast(res.message);
          this.isLoading = false;
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.comments-from-box {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  .content {
    flex: 1;
    overflow: auto;
    .input {
      padding: 0 30px 30px;
      .van-field {
        padding: 30px 27px;
        border-radius: 8px;
        background-color: #f9f9f9;
      }
    }
    .upload {
      margin: 0 30px;
      .images {
        width: 166px;
        height: 166px;
        position: relative;
        box-sizing: border-box;
        background-color: #f7f8fa;
        border-radius: 8px;
        .photograph {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .van-uploader__preview-delete {
          font-size: 32px;
          position: absolute;
          top: -12px;
          background-color: #fff;
          color: #98979d;
          right: -12px;
          z-index: 999;
        }
      }
    }
    .uploader {
      background-color: #fff;
      padding: 0 30px;
      .van-uploader__upload {
        margin: 0;
        background-color: #fff;
      }
    }
  }
  .addCard {
    color: #fff;
    font-size: 32px;
    text-align: center;
    padding: 30px;
    .btn {
      width: 100%;
      border-radius: 10px;
    }
    .van-button__text {
      color: #fff;
      font-size: 32px;
      &::before {
        display: inline-block;
        font-size: 40px;
        margin-right: 10px;
      }
    }
  }
}
</style>
